package rev4;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import rev3.MyString;
import rev3.NodeMyString;

public class Rev4DHTBootstrapMain2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

	       try {
	        	Rev4DHTBootstrapMain2 dht = new Rev4DHTBootstrapMain2();
	        	dht.setupChordFingers();
	        	
	        } catch (Exception e) {
	            System.err.println("NodeMyString exception:");
	            e.printStackTrace();
	        }
	}
	

	NodeMyString n20, n30;
	// Following are the remote references
	NodeMyString rn20, rn30;
	

	private void setupChordFingers()
	{
		
		try {
			n20 = new NodeMyStringRev4Impl(20);			
			n30 = new NodeMyStringRev4Impl(30);			
				
				
			// Bind the Nodes to the rmi registry
			rn20 = bindNodeToDHT("n20", n20);
			rn30 = bindNodeToDHT("n30", n30);

			MyString ms1 = new MyString("mike", "michalak", "89");
			((NodeMyStringRev4Impl)n30).map.put("mike", ms1);

		} catch (Exception e) {
			System.out.println("ERROR in test setupChordFingers():");
			e.printStackTrace();
		}
	}
	
	public NodeMyString bindNodeToDHT(String name, NodeMyString n1)
	{
		NodeMyString comp = null;
		try {
            NodeMyString stub = (NodeMyString) UnicastRemoteObject.exportObject(n1, 0);
            
            Registry registry = LocateRegistry.getRegistry();
            //NodeMyString.class.getProtectionDomain().getCodeSource().getLocation();
            registry.rebind(name, stub);
            // Get the remote ref
            comp = (NodeMyString) registry.lookup(name);
            System.out.println("node "+name+" bound");
            
        } catch (Exception e) {
            System.err.println("NodeMyString exception:");
            e.printStackTrace();
        }
        
        return comp;
	}
}
